package com.chookss.video.recommend;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.VideoFragment;
import com.chookss.video.entity.VideoEntity;
import com.chookss.view.CircleImageView;
import com.chookss.wxapi.ShareActivity;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

@SuppressLint("ValidFragment")
public class RecommendedFragment extends VideoFragment {

    public Context mContext;
    SmartRefreshLayout srlView;
    RecyclerView rv;
    LinearLayout  llChoice1, llChoice2;
    ImageView ivChoice1;
    ImageView ivChoice2;
    LinearLayout rlBottom2;
    TextView tvChoice1, tvChoice2;
    private TextView tvEmpty;
    private ImageView ivEmpty;//空布局
    private RecommendedAdapter adapter;
    private List<VideoEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private int connectCourse = -1;//0是单个视频1关联课程
    private Animation animationIn, animationOut;
    private View emptyView;
    public RecommendedFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend, container, false);
        srlView = view.findViewById(R.id.srlView);
        rv = view.findViewById(R.id.rvView);

        rlBottom2 = view.findViewById(R.id.rlBottom2);
        ivChoice1 = view.findViewById(R.id.ivChoice1);
        ivChoice2 = view.findViewById(R.id.ivChoice2);
        llChoice1 = view.findViewById(R.id.llChoice1);
        llChoice2 = view.findViewById(R.id.llChoice2);
        tvChoice1 = view.findViewById(R.id.tvChoice1);
        tvChoice2 = view.findViewById(R.id.tvChoice2);
        llChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(srlView==null){
                    return;
                }
                if (connectCourse == -1 || connectCourse == 1) {
                    connectCourse = 0;
                    ivChoice1.setBackgroundResource(R.drawable.iv_video_select_54);
                    tvChoice1.setTextColor(Color.parseColor("#ffffff"));
                    ivChoice2.setBackgroundResource(R.drawable.iv_course_54);
                    tvChoice2.setTextColor(Color.parseColor("#6fffffff"));
                } else {
                    connectCourse = -1;
                    ivChoice1.setBackgroundResource(R.drawable.iv_video_54);
                    tvChoice1.setTextColor(Color.parseColor("#6fffffff"));
                }
                srlView.autoRefresh();
            }
        });
        llChoice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(srlView==null){
                    return;
                }
                if (connectCourse == -1 || connectCourse == 0) {
                    connectCourse = 1;
                    ivChoice2.setBackgroundResource(R.drawable.iv_course_select_54);
                    tvChoice2.setTextColor(Color.parseColor("#ffffff"));
                    ivChoice1.setBackgroundResource(R.drawable.iv_video_54);
                    tvChoice1.setTextColor(Color.parseColor("#6fffffff"));
                } else {
                    connectCourse = -1;
                    ivChoice2.setBackgroundResource(R.drawable.iv_course_54);
                    tvChoice2.setTextColor(Color.parseColor("#6fffffff"));
                }
                srlView.autoRefresh();
            }
        });
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initView() {

    }

    @Override
    public void loadPlayList(boolean isLoadMoreData) {
    }

    private void init() {
        animationIn = AnimationUtils.loadAnimation(mContext, R.anim.red_scale_in);
        animationOut = AnimationUtils.loadAnimation(mContext, R.anim.red_scale_out);
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                rlBottom2.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) srlView.getLayoutParams();
        params.setMargins(0, Utils.getStatusBarHeight(mContext) + Utils.dip2px(mContext, 40), 0, 0);
        srlView.setLayoutParams(params);
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new RecommendedAdapter(R.layout.item_video_recommend, mContext, list);
        rv.setAdapter(adapter);
        emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_empty, rv, false);
        ivEmpty = emptyView.findViewById(R.id.ivEmpty);
        tvEmpty = emptyView.findViewById(R.id.tvEmpty);
        tvEmpty.setText("暂无精选");
        ivEmpty.setBackgroundResource(R.drawable.icon_default_no_video);
        LinearLayout.LayoutParams emptyParams = (LinearLayout.LayoutParams) ivEmpty.getLayoutParams();
        emptyParams.setMargins(0, Utils.dip2px(mContext, 100), 0, 0);
        ivEmpty.setLayoutParams(emptyParams);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    /*正在拖拽*/
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        if (rlBottom2 != null) {
                            if (type == 2) {
                                rlBottom2.setVisibility(View.VISIBLE);
                            } else {
                                stopTimer();
                            }
                        }
                        break;
                    /*滑动停止*/
                    case RecyclerView.SCROLL_STATE_IDLE:
                        if (rlBottom2 == null) {
                            return;
                        }
                        if (type == 2) {
                            animationOut.cancel();
                            animationOut.reset();
                            rlBottom2.setVisibility(View.VISIBLE);
                            //定时器 倒计时
                            startTimer();
                        } else {
                            stopTimer();
                        }

                        break;
                    /*惯性滑动中*/
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        if (rlBottom2 != null) {
                            if (type == 2) {
                                rlBottom2.setVisibility(View.VISIBLE);
                            } else {
                                stopTimer();
                            }
                        }
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy < 0) {
                    //下滑
                    type = 2;
                } else if (dy > 0) {
                    //上拉
                    type = 1;
                }
            }
        });
        srlView.autoRefresh();
    }

    int type = -1;
    /**
     * 调用startTimer()和stopTimer()实行暂停重启倒计时。
     */
    private CountDownTimer countDownTimer;

    /**
     * 开启倒计时
     */
    private void startTimer() {
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(5000, 1000) {
                public void onTick(long millisUntilFinished) {
                }
                public void onFinish() {
                    if (rlBottom2 != null) {
                        rlBottom2.startAnimation(animationOut);//开始动画
                        rlBottom2.setVisibility(View.GONE);
                    }
                }
            };
        }
        countDownTimer.start();
    }

    /**
     * 结束倒计时
     */
    private void stopTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            animationOut.cancel();
            animationOut.reset();
            countDownTimer = null;
        }
        if (rlBottom2 != null) {
            rlBottom2.setVisibility(View.GONE);
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("videoType", "2");
        if (connectCourse > -1) {
            map.put("connectCourse", connectCourse + "");
        }
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<VideoEntity>>>() {
        }.getType(), null, Urls.getVideoRand, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<VideoEntity>>() {
            @Override
            public void onSuccess(List<VideoEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                int oldIndex = list.size();
                if(srlView==null){
                    return;
                }
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex, data.size());
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                        rlBottom2.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                isEnd = true;
                if(srlView==null){
                    return;
                }
                if (list.size() == 0) {
                    adapter.setEmptyView(emptyView);
                    rlBottom2.setVisibility(View.VISIBLE);
                }
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }


    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

    @Override
    public void initImmersionBar() {
    }

    class RecommendedAdapter extends BaseQuickAdapter<VideoEntity, BaseViewHolderEx> {
        private Context context;

        public RecommendedAdapter(int layoutResId, Context context, @Nullable List<VideoEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, VideoEntity item) {
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            RelativeLayout rlTop = helper.getView(R.id.rlTop);
            ImageView ivBg = helper.getView(R.id.ivBg);
            TextView tvTime = helper.getView(R.id.tvTime);
            LinearLayout llFocus = helper.getView(R.id.llFocus);
            ImageView ivFocus = helper.getView(R.id.ivFocus);
            TextView tvNumber = helper.getView(R.id.tvNumber);
            TextView tvTiltle = helper.getView(R.id.tvTiltle);
            TextView tvName = helper.getView(R.id.tvName);
            LinearLayout llShare = helper.getView(R.id.llShare);
            LinearLayout llMore = helper.getView(R.id.llMore);
            LinearLayout llPl = helper.getView(R.id.llPl);
            TextView tvShare = helper.getView(R.id.tvShare);
            TextView tvPl = helper.getView(R.id.tvPl);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) rlTop.getLayoutParams();
            params.height = Utils.getScreenWidthPixel(mContext) / 2;
            rlTop.setLayoutParams(params);

            tvTime.setText(Utils.changeTime(item.videoSeconds));
            tvNumber.setText(Utils.changeCounts(item.videoPlayCounts) + "次播放");
            GlideUtils.loadCenterCrop(mContext, item.videoCoverPath, ivBg, R.drawable.icon_video_long);
            GlideUtils.loadAvatar(mContext, item.headPhotoThumbUrl, ivHead);
            tvName.setText(item.employeeName);
            if (Utils.isNull(item.courseCode)) {
                tvTiltle.setText(item.videoTitle);
            } else {
                tvTiltle.setText(item.courseName);
            }
            tvShare.setText(Utils.changeCounts(item.videoShareCounts));
            tvPl.setText(Utils.changeCounts(item.videoCommentCounts));
            if ("1".equals(item.youIsfans)) {
                ivFocus.setBackgroundResource(R.drawable.iv_focus_24);
            } else {
                ivFocus.setBackgroundResource(R.drawable.iv_add_24);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, VedioDetailActivity.class);
                    intent.putExtra("video", item);
                    startActivity(intent);
                }
            });
            llPl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, VedioDetailActivity.class);
                    intent.putExtra("video", item);
                    intent.putExtra("index",2);
                    startActivity(intent);
                }
            });
            llMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, VedioDetailActivity.class);
                    intent.putExtra("video", item);
                    startActivity(intent);
                }
            });
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if (Utils.isNull(item.courseCode)) {
                        Intent intent = new Intent(mContext, PersonalHomeActivity.class);
                        intent.putExtra("employeeCode", item.employeeCode);
                        startActivity(intent);
                    }

                }
            });
            llFocus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if ("1".equals(item.youIsfans)) {
                        toFollow(item.employeeCode, "0");
                    } else {
                        toFollow(item.employeeCode, "1");
                    }


                }
            });
            llShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(context, ShareActivity.class);
                    intent.putExtra("title", item.videoTitle);
                    intent.putExtra("createEmployeeName", item.employeeName);
                    intent.putExtra("content", item.videoKeyWord);
                    intent.putExtra("resourceId", item.videoId);
                    intent.putExtra("videoShareCounts", item.videoShareCounts);
                    intent.putExtra("time", item.videoSeconds);
                    intent.putExtra("picUrl", item.videoCoverPath);
                    intent.putExtra("resourceType", 2);
                    context.startActivity(intent);
                }
            });
        }
    }

    private void toFollow(String employeeCode, String type) {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("employeeCode", employeeCode);
        allmap.put("followStatus", type);
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.toFollow, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                    if ("1".equals(type)) {
                        MyToast.show("关注成功");
                        refreshData(employeeCode, "1");
                    } else {
                        MyToast.show("取消关注");
                        refreshData(employeeCode, "0");
                    }

                } else {
                    MyToast.show(reObject.getString("msg"));
                }

            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void refreshData(String employeeCode, String type) {
        for (int i = 0; i < list.size(); i++) {
            if (employeeCode.equals(list.get(i).employeeCode)) {
                list.get(i).youIsfans = type;
                adapter.notifyItemChanged(i);
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("videoId")) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).videoId.equals(map.get("videoId"))) {
                        if (map.containsKey("totalCommentNum")) {
                            list.get(i).videoCommentCounts = map.get("totalCommentNum");
                            adapter.notifyItemChanged(i);
                        }
                    }
                }
            }
        }
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("videoId")) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).videoId.equals(map.get("videoId"))) {
                        if (map.containsKey("videoCollectCounts")) {
                            list.get(i).videoCollectCounts = map.get("videoCollectCounts");
                        }
                        if (map.containsKey("videoLikeCounts")) {
                            list.get(i).videoLikeCounts = map.get("videoLikeCounts");
                        }
                        if (map.containsKey("isCollect")) {
                            list.get(i).isCollect = map.get("isCollect");
                        }
                        if (map.containsKey("isLike")) {
                            list.get(i).isLike = map.get("isLike");
                        }
                        if (map.containsKey("videoPlayCounts")) {
                            list.get(i).videoPlayCounts = map.get("videoPlayCounts");
                            adapter.notifyItemChanged(i);
                        }
                        if (map.containsKey("videoShareCounts")) {
                            list.get(i).videoShareCounts = map.get("videoShareCounts");
                            adapter.notifyItemChanged(i);
                        }
                        if (map.containsKey("totalCommentNum")) {
                            list.get(i).videoCommentCounts = map.get("totalCommentNum");
                            adapter.notifyItemChanged(i);
                        }
                    }
                }
            } else if (map.containsKey("shapeEmployeeCode")) {
                for (int i = 0; i < list.size(); i++) {
                    if (map.get("shapeEmployeeCode").equals(list.get(i).employeeCode)) {
                        list.get(i).youIsfans = map.get("focusType");
                        adapter.notifyItemChanged(i);
                    }
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("refreshAccount".equals(msg)) {
                //更新账户了
                isEnd = false;
                currentPage = 1;
                getData();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
    }
}
